import { ref } from 'vue'
import Bus from '@/utils/bus'

export function usePipe({ AMap, mapInstance, emits }) {
  const pipes = ref([])
  const selectedPipe = ref(null)

  // 清除所有管线
  function clearPipes() {
    pipes.value.forEach((pipe) => {
      pipe.setMap(null)
    })
    pipes.value = []
    selectedPipe.value = null
  }

  // 创建管线
  function createPipe(line) {
    if (line.coordinates[0][0] == null || line.coordinates[0][1] == null)
      return

    const pipe = new AMap.value.Polyline({
      path: line.coordinates,
      strokeColor: line.color || '#FF0000',
      strokeWeight: 3,
      strokeOpacity: 0.8,
      strokeStyle: line.isDottedSolid === 1 ? 'solid' : 'dashed',
      extData: line,
      bubble: true,
    })

    pipe.setMap(mapInstance.value)
    pipes.value.push(pipe)
    return pipe
  }

  function onClickPipe(event) {
    Bus.$emit('showPromot', { show: true, deletePipe: true })
    const target = event.target
    const extData = target.getExtData()
    // console.log(target,extData,'--!!!!@@@');

    // 如果之前有选中的线，恢复其样式
    if (selectedPipe.value) {
      const prevLine = selectedPipe.value.getExtData()
      selectedPipe.value.setOptions({
        strokeColor: prevLine.color || '#FF0000',
        strokeWeight: 3,
      })
    }

    // 设置当前线为选中状态
    selectedPipe.value = target

    // 高亮显示选中的线
    target.setOptions({
      strokeColor: '#00FF00', // 选中时变为绿色
      strokeWeight: 5, // 选中时加粗
    })
  }
  function closeClickPipe() {
    pipes.value.forEach((item) => {
      item.off('click', onClickPipe)
    })
    // 将选中的管线设置为未选中状态，恢复其原始样式
    if (selectedPipe.value) {
      const prevLine = selectedPipe.value.getExtData()
      selectedPipe.value.setOptions({
        strokeColor: prevLine.color || '#FF0000',
        strokeWeight: 3,
      })
    }
    selectedPipe.value = null

    Bus.$emit('showLayerControl', true)
    Bus.$emit('refreshTool', true)
    Bus.$emit('showPromot', { show: false })
  }
  function openClickPipe() {
    pipes.value.forEach((item) => {
      item.on('click', onClickPipe)
    })
  }
  // 删除选中的
  function onDeletePipe() {
    if (!selectedPipe.value)
      return

    const extData = selectedPipe.value.getExtData()
    console.log('删除管线extData', extData)

    if (extData && extData.id) {
      emits('deleteline', { id: extData.id })
      closeClickPipe()
    }
    else {
      console.error('无法删除管线：缺少ID信息')
    }
  }

  // 更新管线
  function updatePipes(lines) {
    if (!lines || !lines.length)
      return

    lines.forEach((line) => {
      createPipe(line)
    })
  }

  return {
    pipes,
    clearPipes,
    createPipe,
    updatePipes,
    onDeletePipe,
    selectedPipe,
    openClickPipe,
    closeClickPipe,
  }
}
